package com.muki.contentSeen;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class ContentFactory {

	private static final ConcurrentMap<String,BlockingQueue<Content>> memory = new ConcurrentHashMap<>();
	private static final Logger log = Logger.getLogger(ContentFactory.class);
	
	public static Content receive(String topic,int depth,String url,String content) {
		Content c = new Content(topic,depth,url,content);
		BlockingQueue<Content> list = memory.getOrDefault(topic, new ArrayBlockingQueue<>(1000));
		try {
			list.put(c);
			memory.put(topic, list);
			StringBuilder sb = new StringBuilder();
			sb.append(topic+" | ");
			sb.append(depth+" | ");
			sb.append(url+" | ");
			sb.append(content.length());
			log.info(sb.toString());
			return c;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Content getContent(String topic) {
		BlockingQueue<Content> list = memory.getOrDefault(topic,null);
		if(list==null)
			return null;
		try {
			return list.take();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
			
	}
	
	public static void save(ContentPersistant cp,Content content) {
		cp.persistant(content);
	}
	
}
